package com.easysoft.framework.action;

import com.easysoft.commons.utils.CheckFile;
import com.easysoft.commons.utils.StringUtils;
import com.easysoft.commons.utils.WebConstants;
import com.easysoft.framework.annotation.logs.SystemControllerLog;
import com.easysoft.framework.article.model.SysArticle;
import com.easysoft.framework.article.model.SysArticleCategoryView;
import com.easysoft.framework.article.model.SysArticleQuery;
import com.easysoft.framework.article.model.SysArticleView;
import com.easysoft.framework.article.service.ArticleCategoryService;
import com.easysoft.framework.article.service.ArticleService;
import com.easysoft.framework.beans.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 文章内容
 *
 */
@RestController
@RequestMapping(value = SystemArticleAction.BASE_VIEW)
public class SystemArticleAction {

    public static final String BASE_VIEW = "/article";
    private final static Logger logger = LoggerFactory.getLogger(SystemArticleAction.class);

    @Autowired
    @Qualifier("service.ArticleService")
    private ArticleService articleService;

    @Autowired
    @Qualifier("service.ArticleCategoryService")
    private ArticleCategoryService articleCategoryService;

    /**
     * 分页查询文章列表
     *
     * @param page  分页参数
     * @param query 查询条件参数
     * @return 文章的list集合
     */

    @RequestMapping(value = "/listArticle", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView listArticle(Page page, SysArticleQuery query) {
        logger.info("Call SystemArticleAction.listArticle({},{})", page.toString(), query.toString());

        List<SysArticleView> listArticle = articleService.selectSysArticleListByPage(page, query);

        ModelAndView mv = new ModelAndView(BASE_VIEW + "/listArticle");
        mv.addObject("page", page); // 返回分页
        mv.addObject("query", query);// 查询条件
        mv.addObject("listArticle", listArticle); // 返回查询结果集
        return mv;
    }

    /**
     * 跳转文章编辑页面
     *
     * @param id 文章编号
     */
    @RequestMapping(value = "/editSysArticle")
    public ModelAndView editSysArticle(String action,String id) {
        logger.info("Call SystemArticleAction.editSysArticle({},{})", id,action);
        ModelAndView mv = new ModelAndView(BASE_VIEW + "/editArticle");
        List<SysArticleCategoryView> listSysArticleCategory=articleCategoryService.selectAllCategory();
        if(StringUtils.isNotNullAndBlank(id) && StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("update")){
            SysArticle article = articleService.selectByPrimaryKey(id);
            if (article == null) {
                return mv;
            }
            mv.addObject("article",article);
        }
        mv.addObject("listSysArticleCategory",listSysArticleCategory);
        return mv;
    }

    /**
     * 添加文章信息
     *
     * @param article 文章信息
     */
    @RequestMapping(value = "/addSysArticle", method = RequestMethod.POST)
    public int addSysArticle(String action,SysArticle article,@RequestParam(value="multipartFile", required=false)MultipartFile multipartFile,HttpServletRequest request, HttpSession session) {
        logger.info("Call SystemArticleAction.addSysArticle({},{})",action,article.toString());
        article.setOperator((String) session.getAttribute(WebConstants.SESSION_USER_ID));
        // 执行保存操作
        if(multipartFile != null && !("").equals(multipartFile)){
            article.setArticleImage( saveArticlePic(multipartFile,article.getCategoryId(),request));
        }
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("add")) {

            return articleService.addByPrimaryKeyWithBLOBs(article);
        }
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("update")) {

            return articleService.updateByPrimaryKeyWithBLOBs(article);
        }
        return 0;
    }


    /**
     * @param request
     * @param type       类型
     * @param sourceFile 上传的列表文件
     * @param currNum    文件名
     * @return 图片访问路径
     */
    public String uploadImg(HttpServletRequest request, String type, MultipartFile sourceFile, String currNum) {
        if (!sourceFile.isEmpty()) {
            // 文件保存目录路径
            String savePath = request.getSession().getServletContext().getRealPath("/") + "/images/list" + type + "/";
            String saveUrl = request.getContextPath() + "/images/list" + type + "/";
            // 目录不存在则创建
            File uploadPath = new File(savePath);
            if (!uploadPath.exists()) {
                uploadPath.mkdirs();
            }
            String fileName = sourceFile.getOriginalFilename();
            String dir = fileName.substring(fileName.indexOf("."), fileName.length());
            fileName = currNum + dir;
            try {
                // 文件保存路径
                String filePath = savePath + fileName;
                // 转存文件
                sourceFile.transferTo(new File(filePath));
                return saveUrl + fileName;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    /**
     * 保存并且上传列表图片
     * @param multipartFile
     * @param categoryId
     * @param request
     * @return
     */
    public String  saveArticlePic(@ModelAttribute MultipartFile multipartFile, String categoryId, HttpServletRequest request) {
        // 判段是否图片
        InputStream in = null;
        Boolean isPicture = false;
        if (multipartFile != null && !("").equals(multipartFile)) {
            try {
                in = multipartFile.getInputStream();
                isPicture = CheckFile.isPicture(in);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            if (isPicture) {
                String currNum = String.valueOf(System.currentTimeMillis());
                return uploadImg(request, categoryId, multipartFile, currNum);
            }
        }
        return null;
    }


    /**
     *
     * 获取单个文章
     * @param id
     * @return
     */
    @RequestMapping(value = "/viewArticleById", method = RequestMethod.POST)
    public SysArticle viewArticleById(String id) {
        logger.info("Call SystemArticleAction.viewArticleById({})"+id);
        return articleService.selectByPrimaryKey(id);
    }

    /**
     * 更新文章信息
     *
     * @param article 文章信息
     */
    @RequestMapping(value = "/updaterArticleStatus", method = RequestMethod.POST)
    @SystemControllerLog(description = "更新文章信息")
    public int updaterArticleStatus(SysArticle article,@RequestParam(value="multipartFile", required=false)MultipartFile multipartFile, HttpSession session,HttpServletRequest request) {
        logger.info("Call SystemArticleAction.updateSysArticle()");
        article.setOperator((String) session.getAttribute(WebConstants.SESSION_USER_ID));
        if(multipartFile != null && !("").equals(multipartFile)){
            article.setArticleImage( saveArticlePic(multipartFile,article.getCategoryId(),request));
        }
        return articleService.updateByPrimaryKeyWithBLOBs(article);

    }

    /**
     * 删除文章
     *
     * @param id 文章编号
     */
    @RequestMapping(value = "/deleteSysArticle", method = RequestMethod.POST)
    @SystemControllerLog(description = "删除文章")
    public int deleteSysArticle(String id) {
        logger.info("Call SystemArticleAction.deleteSysArticle({})", id);
        return  articleService.deleteByPrimaryKey(id);
    }
}
